import { shopAdmin, goodClass, shopPageList, apiGetBannerById, apiGetPCDDate, apiRedImages, getUpdateLevelByUid, apiGetIndexGoodsCategoryList, apiGetMessageNotice, apiAddReceiveRed } from '../../api/index'

let app = getApp()
let showTime
Page({
  /**
   * 页面的初始数据
   */
  data: {
    scrollLeftValue: 0,
    // 是否显示授权弹窗
    commend: true,
    // 轮播图
    shopBanner: [],
    // 分类商品
    shopClasses: [],
    selectType: 0,
    goodsGroupImg: '',
    pageNum: 1,
    // 加载更多
    isMore: false,
    showSourId: 0,
    // 导航名称
    navNAme: '',
    shopPromise: [
      { name: '自营电商' },
      { name: '正品保证' },
      { name: '7天退换货' },
      { name: '全场包邮' }
    ],
    shopHotGoods: [],
    leftGoodsData: [],
    rightGoodsData: [],
    showModule: [
      { img: '../../images/ic_home_red@3x.png', name: '新人红包' },
      { img: '../../images/ic_home_specialty@3x.png', name: '助力拿现金' },
      { img: '../../images/ic_home_returnmoney@3x.png', name: '多拿会员' },
      { img: '../../images/ic_home_ticket@3x.png', name: '领券中心' }
    ],
    // 显示返回顶部按钮
    showTotop: false,
    goodGroup: [],
    // 添加小程序提示
    showTopTip: false,
    redNum: 0,
    index: 0,
    showData: [],
    show: '',
    loads: true
  },
  // 导航栏滚动偏移
  autoScrollTopNav (idx, id) {
    let scrollLeftValue = 0
    if (idx > 2) {
      scrollLeftValue = (idx - 2) * 80
    }
    this.setData({
      scrollLeftValue: scrollLeftValue
    })
  },
  // 跳转到搜索
  toSearch () {
    wx.navigateTo({
      url: '../shopping-search/shopping-search'
    })
  },
  // 检测是否授权
  changeAuthStatus (e) {
    let showRed = false
    this.getRed = e.detail.getRed
    if (e.detail.getRed === 0) {
      showRed = true
    }
    this.setData({
      commend: e.detail.status,
      showRed
    })
    this.getSourId(this.sourId)
    if (e.detail.status === false) {
      wx.showTabBar()
    }
  },
  getSourId (id) {
    getUpdateLevelByUid({ source_uid: id }).then(
      res => {})
  },
  // 获取商品分类
  getGoodClass () {
    goodClass().then(
      res => {
        if (res.data[0].category_id) {
          this.setData({
            pageNum: 1,
            showTopTip: true,
            shopHotGoods: [],
            leftGoodsData: [],
            rightGoodsData: [],
            selectType: res.data[0].category_id,
            shopClasses: res.data,
            category_name: res.data[0].short_name,
            description: res.data[0].description
          })
          this.getHomeData()
          this.getHomeMsg()
        }
      }
    )
  },
  // 获取首页分类模块商品
  getHomeClass () {
    apiGetIndexGoodsCategoryList().then(
      res => {
        for (let i = 0; i < res.data.length; i++) {
          let data = res.data[i].goods_list
          for (let j = 0; j < data.length; j++) {
            data[j].promotion_price = (Math.round(data[j].promotion_price * 100) / 100).toString()
          }
          if (res.data[i].goods_list.length % 2 === 0 && res.data[i].goods_list.length > 0) {
            res.data[i].goods_list[0].even = 2
          }
          if (res.data[i].goods_list.length === 0) {
            res.data[i].flag = false
          } else {
            res.data[i].flag = true
          }
        }
        this.setData({
          homeClass: res.data
        })
      }
    )
  },
  // 进入更多分类
  toGoodsClass (e) {
    let data = {
      category_id: e.detail.item.category_id,
      category_name: e.detail.item.short_name,
      description: e.detail.item.description
    }
    wx.navigateTo({
      url: `../home-class/home-class?data=${JSON.stringify(data)}`
    })
  },
  // 分类点击
  changeType (e) {
    this.data.navNAme = e.currentTarget.dataset.name
    let id = e.target.dataset.id
    // 判断是否存在id
    if (id === this.data.selectType) {
      return
    }
    if (e.target.dataset.name === '推荐') {
      this.getHomeMsg()
      this.setData({
        category_name: this.data.shopClasses[0].category_name,
        description: this.data.shopClasses[0].description
      })
    }
    let idx = e.currentTarget.dataset.index
    this.navLock = true
    this.autoScrollTopNav(idx, id)
    this.setData({
      pageNum: 1,
      selectType: id,
      shopHotGoods: []
    })
    this.getBanner()
    this.getTypeData()
  },
  getHomeData () {
    this.getBanner()
    this.getTypeData()
  },
  // 商城首页
  getHomeMsg () {
    shopAdmin().then(
      res => {
        const goodsGroup = res.data.goods_group_data.list
        this.data.goodGroup = res.data.goods_group_data.list
        let len = goodsGroup.length > 7 ? 7 : goodsGroup.length
        let imageGroup = {}
        for (let i = 0; i < len; i++) {
          let key = i === 0 ? 'goodsGroupImg' : 'goodsGroupImg' + i
          imageGroup[key] = goodsGroup[i].group_pic
        }
        this.setData(imageGroup)
        wx.stopPullDownRefresh()
      }
    )
  },
  toHotGood (e) {
    for (let i = 0; i < this.data.goodGroup.length; i++) {
      if (e.currentTarget.dataset.index === i) {
        if (this.data.goodGroup[i].group_dec !== '') {
          wx.navigateTo({
            url: `../goods-detail/goods-detail?id=${this.data.goodGroup[i].group_dec}`
          })
        }
      }
    }
  },
  // 分类轮播图
  getBanner () {
    apiGetBannerById({ category_id: this.data.selectType }).then(
      res => {
        let showImg = false
        let showOneImg
        if (res.data.length === 1) {
          showImg = true
          showOneImg = res.data[0].adv_image
        }
        this.setData({
          shopBanner: res.data,
          showImg,
          showOneImg: showOneImg || ''
        })
      })
  },
  // 轮播图跳转详情
  toGoodsDetail (e) {
    console.log(e)
    if (e.detail.id - 0 !== 0) {
      wx.navigateTo({
        url: e.detail.id
      })
    }
  },
  getTypeData () {
    // 商品分页列表
    shopPageList({ category_id: this.data.selectType, page: this.data.pageNum }).then(
      res => {
        for (let i = 0; i < res.data.data.length; i++) {
          // res.data.data[i].make_money = (res.data.data[i].make_money - 0).toFixed(2)
          res.data.data[i].promotion_price = (Math.round(res.data.data[i].promotion_price * 100) / 100).toString()
        }
        let isMore = false
        let data = this.data.shopHotGoods
        if (res.data.data.length >= 20) {
          isMore = true
        } else {
          isMore = false
        }
        this.setData({
          shopHotGoods: data.concat(res.data.data),
          isMore,
          loads: false
        })
        this.setWaterpullData(res.data.data)
        wx.stopPullDownRefresh()
      }
    )
  },
  setWaterpullData (data) {
    data.forEach(item => {
      var query = wx.createSelectorQuery()
      query.select('#goodsRight').boundingClientRect()
      query.selectViewport().scrollOffset()
    })
  },
  // 跳转商品详情
  goToDetails (e) {
    wx.navigateTo({
      url: `../goods-detail/goods-detail?id=${e.detail}`
    })
  },
  getRedStatus () {
    apiAddReceiveRed().then(
    ).catch(
      res => {
        this.redStatus = res.data.code
      }
    )
  },
  //  模块点击
  clickType (e) {
    let index = e.currentTarget.dataset.index
    switch (index) {
      case 0:
        if (this.redStatus && this.redStatus === -1) {
          wx.navigateTo({
            url: `../receive-red/receive-red`
          })
        } else {
          this.setData({
            showRed: true
          })
        }
        break
      case 1:
        wx.navigateTo({
          url: '../assistance/assistance'
        })
        break
      case 2:
        wx.navigateTo({
          url: '../distribution-center/distribution-center'
        })
        break
      case 3:
        wx.navigateTo({
          url: '../coupon/coupon'
        })
        break
    }
  },
  /**
   * 生命周期函数--监听页面加
   */
  onLoad (options) {
    if (options.source_uid) {
      this.sourId = options.source_uid
    }
    this.init()
    this.getRedStatus()
    this.getData()
    this.getPCDDate()
    apiRedImages().then(
      res => {
        this.setData({
          openImgs: res.data
        })
      }
    )
    this.timer = setInterval(
      () => {
        this.animations()
      }, 6000)
  },
  // 获取用户购物提示
  getData () {
    apiGetMessageNotice().then(
      res => {
        this.setData({
          showData: res.data
        })
      }
    )
  },
  // 动画显示
  animations () {
    this.data.index++
    if (this.data.index === this.data.showData.length) {
      this.data.index = 0
    }
    this.setData({
      show: this.data.showData[this.data.index]
    })
    setTimeout(() => {
      this.setData({
        show: ''
      })
    }, 4000)
  },
  init () {
    this.setData({
      isIphoneX: app.globalData.isIphoneX,
      pageNum: 1,
      navHeight: app.globalData.navHeight,
      iPad: app.globalData.iPad
    })
    this.getGoodClass()
    this.getHomeClass()
  },
  // 监听页面滚动
  onPageScroll (e) {
    if (e.scrollTop > 200) {
      this.setData({
        showTotop: true
      })
    } else {
      this.setData({
        showTotop: false
      })
    }
  },
  // 返回顶部
  goTop () {
    wx.pageScrollTo({
      scrollTop: 0
    })
  },
  // 获取省市
  getPCDDate () {
    if (!wx.getStorageSync('cityData')) {
      apiGetPCDDate().then(
        res => {
          wx.setStorage({
            key: 'cityData',
            data: res.data
          })
        }
      )
    }
  },
  hadRed () {
    this.data.redNum = 0
    wx.navigateTo({
      url: '../receive-red/receive-red'
    })
  },
  redcancels () {
    this.data.redNum = 1
    this.setData({
      showRed: false
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady () {
    showTime = setTimeout(
      () => {
        this.setData({
          showTopTip: false
        })
      }, 8000)
  },
  // 跳转多赚
  toMakeMore () {
    wx.navigateTo({
      url: '../red-share/red-share'
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide () {
    clearTimeout(showTime)
    this.setData({
      showRed: false,
      showTopTip: false
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload () {
    clearTimeout(showTime)
    clearInterval(this.timer)
    this.setData({
      showRed: false,
      showTopTip: false
    })
  },
  onShow () {
    if (this.data.commend === true) {
    } else {
      this.data.commend = false
      this.setData({
        commend: false
      })
      wx.showTabBar()
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh () {
    this.setData({
      pageNum: 1,
      shopHotGoods: []
    })
    if (!this.data.navNAme || this.data.navNAme === '推荐') {
      this.getHomeMsg()
    }
    this.getTypeData()
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom () {
    if (this.data.isMore) {
      let pageNum = this.data.pageNum
      pageNum++
      this.setData({
        pageNum
      })
      this.getTypeData()
    }
  }
})
